﻿using System.Text.RegularExpressions;
using System.Windows.Controls;

namespace UI.Validators
{
    /// <summary>
    /// Regular Expression validator rule for user input
    /// </summary>
    public class RegExValidationRule : ValidationRule
    {
        /// <summary>
        /// Default RegEx options
        /// </summary>
        RegexOptions _options = RegexOptions.Compiled;

        /// <summary>
        /// Gets or sets the RegEx expression.
        /// </summary>
        /// <value>The RegEx expression.</value>
        public string Expression { get; set; }
        /// <summary>
        /// Gets or sets the RegEx options.
        /// </summary>
        /// <value>The RegEx options.</value>
        public RegexOptions Options { 
            get
            {
                
                return _options;
            }
            set
            {
                _options = value;
            }
        }
        /// <summary>
        /// Gets or sets the error message.
        /// </summary>
        /// <value>The error message.</value>
        public string ErrorMessage { get; set; }

        /// <summary>
        /// When overridden in a derived class, performs validation checks on a value.
        /// </summary>
        /// <param name="value">The value from the binding target to check.</param>
        /// <param name="cultureInfo">The culture to use in this rule.</param>
        /// <returns>
        /// A <see cref="T:System.Windows.Controls.ValidationResult"/> object.
        /// </returns>
        public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
        {
            if(string.IsNullOrEmpty(Expression))
            {
                return new ValidationResult(true, null);
            }

            string inputString = value as string;

            if(string.IsNullOrEmpty(inputString))
            {
                return new ValidationResult(true, null); 
            }
            
            Regex regex = new Regex(Expression, _options);
            if (regex.IsMatch(inputString))
            {
                return new ValidationResult(true, null);
            }
            else
            {
                return new ValidationResult(false, ErrorMessage);
            }
        }
    }
}
